from app import app, db
from models import *
from flask import request, url_for, redirect, flash, render_template
from flask_security import SQLAlchemyUserDatastore, Security, current_user, login_required
from flask_security.utils import login_user, logout_user
import forms
import datetime, time

# 后端处理文件
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)

security = Security(app, user_datastore)
db.create_all()


@app.route('/', methods=['GET', 'POST'])
def index():
    nowtrue = Staff.query.filter_by(now=True).all()
    nowfalse = Staff.query.filter_by(now=False).all()

    men = Staff.query.filter_by(sex='男').all()
    women = Staff.query.filter_by(sex='女').all()
    now_h = datetime.datetime.now().strftime('%H')
    now_h=int(now_h)
    return render_template('index.html', nowtrue=nowtrue, nowfalse=nowfalse, men=men, women=women,now_h=now_h)

# -----------------------------------------------
"""
打卡sign(登录或注册自动进行打卡)--点击打卡
        -- 检测是否已打卡
        current_user.userID
"""
@app.route('/sign') #只接受post请求
@login_required # 登录保护
def sign():
    userID=current_user.userID
    now_day = datetime.datetime.now().strftime('%Y-%m-%d')
    day = Sign_in.query.filter_by(late_date=now_day).first()
    staffs=Staff.query.filter_by().all()
    if day is None:
        db.session.bulk_insert_mappings(
            Sign_in,
            [
                dict(userID=staff.userID,late_date=now_day)
                for staff in staffs
            ]
        )
        db.session.commit()
        db.session.bulk_insert_mappings(
            Overtime,[
                dict(userID=staff.userID,overtime_date=now_day)
                for staff in staffs
            ]
        )
        db.session.commit()
    sign_in = Sign_in.query.filter_by(userID=userID,late_date=now_day).first()
    if sign_in.late_time == -1:
        now_h = datetime.datetime.now().strftime('%H')
        hour = int(now_h) - 9
        now_m = datetime.datetime.now().strftime('%M')
        m = int(now_m) / 60
        m = round(m, 1)
        hour = hour + m
        if hour >= 1:
            sign_in.late_time=hour
            db.session.commit()
            flash('打卡成功(迟到！！！)')
        else:
            sign_in.late_time=0
            db.session.commit()
            flash('打卡成功')
    else:
        flash('今日已打卡')

    return redirect(url_for('index'))

#----------------------------------------
"""
下班打卡 点击打卡 自动记录是否加班、早退，自动记录加班时间
"""
@app.route('/off_duty') #只接受post请求
@login_required # 登录保护
def off_duty():
    userID=current_user.userID
    now_day = datetime.datetime.now().strftime('%Y-%m-%d')
    overtime = Overtime.query.filter_by(userID=userID, overtime_date=now_day).first()
    if overtime.overtime_hour == -1:
        now_h = datetime.datetime.now().strftime('%H')
        hour = int(now_h) - 17
        now_m = datetime.datetime.now().strftime('%M')
        m = int(now_m) / 60
        m = round(m, 1)
        hour = hour + m
        if hour >= 1:
            overtime.overtime_hour=hour
            db.session.commit()
            flash('打卡成功(加班辛苦了！)')
        elif hour >=0 and hour <= 1:
            overtime.overtime_hour=0
            db.session.commit()
            flash('打卡成功')
        else:
            flash('打卡失败，请不要早退')
    else:
        flash('今日已打卡')

    return redirect(url_for('index'))


"""
 负责的功能
 注册--logging
 登录--login
 登出--logout
 权限管理--'User','Admin','Root'
 员工入职管理 -- staff --填写/write_staff(user/admin) -- 修改/change_staff(user/Admin) -- 离职处理/dimission(User)(修改now属性为0)
                        --查找/select_staff(userID,username,IDnumber,departmentID,departmentname,)
            -- staff_probation --填写/write_staff_probation(Admin) -- 修改/change_staff_probation(Admin)
 员工离职管理 -- staff_dimission --填写/write_staff_dimission(Admin) -- 修改/change_staff_dimission(Admin)
                            -- 查找/select_staff_dimission(userID,name,departmentname,postname,dimission_type,date)
  
 用户权限管理 -- user_role (Admin/Root)    -- 修改/change_role (提升为管理员，降为普通用户)（Root）
"""


@app.route('/user/login', methods=['GET', 'POST'])
def login():  # 登录
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    form = forms.LoginForm()
    if request.method == 'POST':
        userID = request.form.get('userID')
        password = request.form.get('password')

        if not userID or not password:
            flash('请输入')
            return redirect(url_for('login'))

        user = User.query.filter_by(userID=userID).first()
        if user is None:
            flash('员工号错误')
            return redirect(url_for('login'))
        now = Staff.query.filter_by(now=True, userID=user.userID).first()
        if now is None:
            flash('员工已离职')
            return redirect(url_for('login'))
        if not user.validate_password(password):
            flash('密码错误')
            return redirect(url_for('login'))
        flash('登录成功')
        login_user(user, remember=True)
        return redirect(url_for('index'))
    return render_template('login.html', form=form)


@app.route('/logging', methods=['GET', 'POST'])
def logging():  # 注册
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    if request.method == 'POST':
        userID = request.form.get('userID')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')
        phone = request.form.get('phone')
        staff_phone = User.query.filter_by(phone=phone).first()
        if staff_phone is not None:
            flash('手机号已被注册')
            return redirect(url_for('logging'))
        email = request.form.get('email')
        staff_email = User.query.filter_by(email=email).first()
        if staff_email is not None:
            flash('邮箱已被注册')
            return redirect(url_for('logging'))
        if password1 != password2:
            flash('两次输入的密码不同')
            return redirect(url_for('logging'))
        staff = Staff.query.filter_by(userID=userID).first()
        if staff is None:
            flash('员工号错误')
            return redirect(url_for('logging'))
        now = Staff.query.filter_by(now=True, userID=userID).first()
        if now is None:
            flash('员工已离职')
            return redirect(url_for('logging'))
        user = User.query.filter_by(userID=userID).first()
        if user is not None:
            flash('用户已注册')
            return redirect(url_for('login'))
        user = Staff.query.filter_by(userID=userID).first()
        if user is None:
            flash('用户不存在，请检查员工号')
            return redirect(url_for('logging'))
        new_user = user_datastore.create_user(userID=userID, password=User.set_password(password1), phone=phone,
                                              email=email)
        normal_role = user_datastore.find_role('User')
        db.session.add(new_user)
        user_datastore.add_role_to_user(new_user, normal_role)
        db.session.commit()
        flash('注册成功')
        login_user(new_user)
        return redirect(url_for('index'))
    return render_template('logging.html')


@app.route('/logout')
def logout():  # 登出
    logout_user()
    flash('登出')
    return redirect(url_for('index'))


@app.route('/staff', methods=['GET', 'POST'])
@login_required  # 用于视图保护
def staff():  # 员工基本信息
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date, now=True).first()
                if staffs is None:
                    flash('员工号不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff.html', staffs=staffs, departments=departments, posts=posts, info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date, now=True).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff.html', staffs=staffs, departments=departments, posts=posts, info=info)
            if info == 'IDnumber':
                staffs = Staff.query.filter_by(IDnumber=date, now=True).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff.html', staffs=staffs, departments=departments, posts=posts, info=info)
            if info == 'departmentID':
                staffs = Staff.query.filter_by(departmentID=date, now=True).all()
                if staffs is None:
                    flash('部门号不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('staff'))
                posts = Post.query.all()

                return render_template('staff.html', staffs=staffs, departments=departments, posts=posts, info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('staff'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID, now=True).all()
                posts = Post.query.all()

                return render_template('staff.html', staffs=staffs, departments=departments, posts=posts, info=info)
        staffs = Staff.query.filter_by(now=True).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        return render_template('staff.html', staffs=staffs, departments=departments, posts=posts, info=info)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        posts = Post.query.filter_by(postID=staffs.postID).first()
        return render_template('staff.html', staffs=staffs, departments=departments, posts=posts)


@app.route('/detailed_staff/<int:userID>')
@login_required  # 用于视图保护
def detailed_staff(userID):  # 详细信息
    staff = Staff.query.get_or_404(userID)
    department = Department.query.filter_by(departmentID=staff.departmentID).first()
    post = Post.query.filter_by(postID=staff.postID).first()
    return render_template('detailed_staff.html', staff=staff, department=department, post=post)


@app.route('/write_staff', methods=['GET', 'POST'])
def write_staff():  # 填写员工基本信息
    departments = Department.query.all()
    posts = Post.query.all()
    nations = Nation.query.all()
    if request.method == 'POST':
        if not current_user.is_authenticated:
            return redirect(url_for('index'))
        else:
            username = request.form.get('username')
            sex = request.form.get('sex')
            birthday = request.form.get('birthday')
            IDnumber = request.form.get('IDnumber')
            departmentID = request.form.get('departmentID')
            postID = request.form.get('postID')
            hiredate = request.form.get('hiredate')
            takejobdate = request.form.get('takejobdate')
            employment_form = request.form.get('employment_form')
            personnel_source = request.form.get('personnel_source')
            phone = request.form.get('phone')
            email = request.form.get('email')
            politics_status = request.form.get('politics_status')
            nation = request.form.get('nation')
            native_place = request.form.get('native_place')
            height = request.form.get('height')
            if height == '':
                height = None
            bloodtype = request.form.get('bloodtype')
            marriage = request.form.get('marriage')
            birthplace = request.form.get('birthplace')
            domicileplace = request.form.get('domicileplace')
            highest_degree = request.form.get('highest_degree')
            highest_offering = request.form.get('highest_offering')
            graduate_school = request.form.get('graduate_school')
            major = request.form.get('major')
            graduation_date = request.form.get('graduation_date')
            if graduation_date == '':
                graduation_date = None
            staff_phone = Staff.query.filter_by(phone=phone).first()
            if staff_phone is not None:
                flash('电话号码已存在')
                return redirect(url_for('write_staff'))
            staff_email = Staff.query.filter_by(email=email).first()
            if staff_email is not None:
                flash('邮箱已存在')
                return redirect(url_for('write_staff'))
            print("输入")
            number = Staff.query.filter_by(departmentID=departmentID, postID=postID).count()
            number = number + 1
            if (int(postID) < 10):
                postID = '0' + str(departmentID)
            if (int(number) < 10):
                number = '0' + str(number)
            userID = str(departmentID) + str(postID) + str(number)
            staff = Staff(userID=userID, username=username, sex=sex, birthday=birthday, IDnumber=IDnumber,
                          departmentID=departmentID, postID=postID, hiredate=hiredate,
                          takejobdate=takejobdate, employment_form=employment_form,
                          personnel_source=personnel_source, phone=phone, email=email, now=True,
                          politics_status=politics_status, nation=nation, native_place=native_place,
                          height=height, bloodtype=bloodtype, marriage=marriage, birthplace=birthplace,
                          domicileplace=domicileplace, highest_degree=highest_degree,
                          highest_offering=highest_offering, graduate_school=graduate_school,
                          major=major, graduation_date=graduation_date)
            db.session.add(staff)
            db.session.commit()
            flash('添加成功')
            now_day = datetime.datetime.now().strftime('%Y-%m-%d')
            sign_in=Sign_in(userID=userID,late_date=now_day,late_time=0)
            db.session.add(sign_in)
            db.session.commit()
            overtime = Overtime(userID=userID,overtime_date=now_day,overtime_hour=-1)
            db.session.add(overtime)
            db.session.commit()
            return redirect(url_for('staff'))

    return render_template('write_staff.html', departments=departments, posts=posts, nations=nations)


@app.route('/change_staff/<int:userID>', methods=['GET', 'POST'])
@login_required
def change_staff(userID):  # 修改员工基本信息
    staff = Staff.query.get_or_404(userID)
    departments = Department.query.all()
    posts = Post.query.all()
    nations = Nation.query.all()
    if request.method == 'POST':
        username = request.form.get('username')
        departmentID = request.form.get('departmentID')
        postID = request.form.get('postID')
        employment_form = request.form.get('employment_form')
        phone = request.form.get('phone')
        email = request.form.get('email')
        politics_status = request.form.get('politics_status')
        nation = request.form.get('nation')
        native_place = request.form.get('native_place')
        height = request.form.get('height')
        if height == '':
            height = None
        bloodtype = request.form.get('bloodtype')
        marriage = request.form.get('marriage')
        birthplace = request.form.get('birthplace')
        domicileplace = request.form.get('domicileplace')
        highest_degree = request.form.get('highest_degree')
        highest_offering = request.form.get('highest_offering')
        graduate_school = request.form.get('graduate_school')
        major = request.form.get('major')
        graduation_date = request.form.get('graduation_date')
        if graduation_date == '':
            graduation_date = None
        staff_phone = Staff.query.filter_by(phone=phone).first()
        if staff_phone is not None:
            if staff_phone.userID != userID:
                flash('电话号码已存在')
                return redirect(url_for('change_staff', userID=userID))
        staff_email = Staff.query.filter_by(email=email).first()
        if staff_email is not None:
            if staff_email.userID != userID:
                flash('邮箱已存在')
                return redirect(url_for('change_staff', userID=userID))
        staff.username = username
        staff.departmentID = departmentID
        staff.postID = postID
        staff.employment_form = employment_form
        staff.politics_status = politics_status
        staff.nation = nation
        staff.native_place = native_place
        staff.phone = phone
        staff.email = email
        staff.height = height
        staff.bloodtype = bloodtype
        staff.marriage = marriage
        staff.birthplace = birthplace
        staff.domicileplae = domicileplace
        staff.highest_degree = highest_degree
        staff.highest_offering = highest_offering
        staff.graduate_school = graduate_school
        staff.major = major
        staff.graduation_date = graduation_date
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff'))
    return render_template('change_staff.html', staff=staff, departments=departments, posts=posts, nations=nations)


@app.route('/write_staff_dimission/<int:userID>', methods=['GET', 'POST'])
@login_required
def write_staff_dimission(userID):  # 填写员工离职信息
    staff = Staff.query.get_or_404(userID)
    if request.method == 'POST':
        userID = userID
        termdate = request.form.get('termdate')
        dimission_type = request.form.get('dimission_type')
        leave_to = request.form.get('leave_to')
        talent_pool = request.form.get('talent_pool')
        remark = request.form.get('remark')
        staff_dimission = Staff_dimission(userID=userID, termdate=termdate, dimission_type=dimission_type,
                                          leave_to=leave_to, talent_pool=talent_pool, remark=remark)
        db.session.add(staff_dimission)
        staff.now = False
        db.session.commit()
        flash('修改成功')
        return redirect(url_for('staff'))
    return render_template('/write_staff_dimission.html', staff=staff)


@app.route('/staff_dimission', methods=['GET', 'POST'])
@login_required
def staff_dimission():  # 查看员工离职信息
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date, now=False).first()
                if staffs is None:
                    flash('员工号不存在或员工未离职')
                    return redirect(url_for('staff_dimission'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                staff_dimissions = Staff_dimission.query.filter_by(userID=date).first()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date, now=False).first()
                if staffs is None:
                    flash('员工不存在或员工未离职')
                    return redirect(url_for('staff_dimission'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                staff_dimissions = Staff_dimission.query.filter_by(userID=staffs.userID).first()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID, now=False).all()
                if staffs is None:
                    flash('该部门不存在离职员工')
                    return redirect(url_for('staff_dimission'))
                posts = Post.query.all()
                staff_dimissions = Staff_dimission.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'postname':
                posts = Post.query.filter_by(postname=date).first()
                if posts is None:
                    flash('岗位不存在')
                    return redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(postID=posts.postID, now=False).all()
                if staffs is None:
                    flash('该岗位不存在离职员工')
                    return redirect(url_for('staff_dimission'))
                departments = Department.query.all()
                staff_dimissions = Staff_dimission.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'dimission_type':
                staff_dimissions = Staff_dimission.query.filter(
                    Staff_dimission.dimission_type.like('%{date}%'.format(date=date))).all()
                if staff_dimissions is None:
                    flash('该类型没有离职员工')
                    return redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(now=False).all()
                departments = Department.query.all()
                posts = Post.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'termdate':
                staff_dimissions = Staff_dimission.query.filter(Staff_dimission.termdate <= date).all()
                if staff_dimissions is None:
                    flash('该时间之前没有离职员工')
                    return redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(now=False).all()
                departments = Department.query.all()
                posts = Post.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
        staff_dimissions = Staff_dimission.query.all()
        staffs = Staff.query.filter_by(now=False).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        return render_template('/staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                               departments=departments, posts=posts, info=info)


@app.route('/change_staff_dimission/<int:userID>', methods=['GET', 'POST'])
@login_required
def change_staff_dimission(userID):  # 修改员工离职信息
    staff = Staff.query.get_or_404(userID)
    staff_dimission = Staff_dimission.query.filter_by(userID=userID).first()
    if staff_dimission is None:
        flash('员工未离职')
        return redirect(url_for('staff_dimission'))

    if request.method == 'POST':
        dimission_type = request.form.get('dimission_type')
        leave_to = request.form.get('leave_to')
        remark = request.form.get('remark')
        staff_dimission.dimission_type = dimission_type
        staff_dimission.leave_to = leave_to
        staff_dimission.remark = remark
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff_dimission'))
    return render_template('change_staff_dimission.html', staff=staff, staff_dimission=staff_dimission)


@app.route('/user_role', methods=['GET', 'POST'])
@login_required
def user_role():
    if current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date, now=True).first()
                if staffs is None:
                    flash('员工号不存在或已离职')
                    return redirect(url_for('user_role'))
                users = User.query.filter_by(userID=date).first()

                return render_template('user_role.html', users=users, staffs=staffs, info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date, now=True).first()
                if staffs is None:
                    flash('员工号不存在或已离职')
                    return redirect(url_for('user_role'))
                users = User.query.filter_by(userID=staffs.userID).first()

                return render_template('user_role.html', users=users, staffs=staffs, info=info)
        users = User.query.all()
        staffs = Staff.query.filter_by(now=True).all()

        info = 1
        return render_template('user_role.html', users=users, staffs=staffs, info=info)
    else:
        flash('请以超级管理员账户登录')
        return redirect(url_for('index'))


@app.route('/promote_role/<int:userID>')
@login_required
def promote_role(userID):  # 升为管理员
    user = User.query.filter_by(userID=userID).first()
    adminrole = user_datastore.find_role('Admin')
    userrole = user_datastore.find_role('User')
    user_datastore.remove_role_from_user(user, userrole)
    user_datastore.add_role_to_user(user, adminrole)
    db.session.commit()
    return redirect(url_for('user_role'))


@app.route('/reduce_role/<int:userID>')
@login_required
def reduce_role(userID):  # 降为普通用户
    user = User.query.filter_by(userID=userID).first()
    adminrole = user_datastore.find_role('Admin')
    userrole = user_datastore.find_role('User')
    user_datastore.remove_role_from_user(user, adminrole)
    user_datastore.add_role_to_user(user, userrole)
    db.session.commit()
    return redirect(url_for('user_role'))


"""
        部门  -- 添加/department_add （Admin/Root）  
              -- 删除部门/department_delete(Admin/Root)  
              -- 修改/department_alter(Admin/Root)
              -- 查找/info （部门编号/部门名称/电话）
              -- 显示/department（所有人）
        岗位  -- 显示/post(所有人)
              -- 添加/post_add(Admin/Root)
              -- 删除/post_delete(Admin/Root)
              -- 修改/post_alter(Admin/Root)
              -- 查找/info()
"""


@app.route('/department', methods=['GET', 'POST'])
@login_required  # 登录保护
def department():
    if request.method == 'POST':
        info = request.form.get('info')
        date = request.form.get('date')
        if info == 'departmentID':
            department = Department.query.filter_by(departmentID=date).first()
            if department is None:
                flash('部门编号不存在')
                return redirect(url_for('department'))
            return render_template('department.html', departments=department, info=info)
        if info == 'departmentname':
            department = Department.query.filter_by(departmentname=date).first()
            if department is None:
                flash('部门不存在')
                return redirect(url_for('department'))
            return render_template('department.html', departments=department, info=info)

        if info == 'departmentphone':
            department = Department.query.filter_by(departmentphone=date).first()
            if department is None:
                flash('电话不存在')
                return redirect(url_for('department'))
            return render_template('department.html', departments=department, info=info)
    departments = Department.query.all()

    return render_template('department.html', departments=departments, info=1)


@app.route('/department_delete/<int:departmentID>', methods=['POST'])
@login_required  # 登录保护
def department_delete(departmentID):
    staff = Staff.query.filter_by(departmentID=departmentID).first()
    if staff is not None:
        flash('该部门内存在员工无法删除')
        return redirect(url_for('department'))
    department = Department.query.get_or_404(departmentID)
    db.session.delete(department)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('department'))


@app.route('/department_alter/<int:departmentID>', methods=['GET', 'POST'])
@login_required
def department_alter(departmentID):
    department = Department.query.get_or_404(departmentID)
    departmentnames = Department.query.all()
    if request.method == 'POST':
        departmentname = request.form.get('departmentname')
        departmenttype = request.form.get('departmenttype')
        departmentphone = request.form.get('departmentphone')
        departmentfax = request.form.get('departmentfax')
        if departmentfax == '':
            departmentfax = None
        describe = request.form.get('describe')
        superior = request.form.get('superior')
        department.departmentname = departmentname
        department.departmenttype = departmenttype
        department.departmentphone = departmentphone
        department.departmentfax = departmentfax
        department.describe = describe
        department.superior = superior
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('department'))

    return render_template('department_alter.html', department=department, departmentnames=departmentnames)


@app.route('/department_add', methods=['GET', 'POST'])
@login_required
def department_add():
    if request.method == 'POST':
        departmentname = request.form.get('departmentname')
        departmenttype = request.form.get('departmenttype')
        departmentphone = request.form.get('departmentphone')
        departmentfax = request.form.get('departmentfax')
        if departmentfax == '':
            departmentfax = None
        describe = request.form.get('describe')
        superior = request.form.get('superior')
        establish = request.form.get('establish')
        department = Department(departmentname=departmentname, departmenttype=departmenttype,
                                departmentphone=departmentphone, departmentfax=departmentfax, describe=describe,
                                superior=superior, establish=establish)

        db.session.add(department)
        db.session.commit()
        flash('新建成功')
        return redirect(url_for('department'))
    departmentnames = Department.query.all()
    return render_template('department_add.html', departmentnames=departmentnames)


@app.route('/post', methods=['GET', 'POST'])
@login_required  # 登录保护
def post():
    if request.method == 'POST':
        info = request.form.get('info')
        date = request.form.get('date')
        if info == 'postID':
            posts = Post.query.filter_by(postID=date).first()
            if posts is None:
                flash('岗位编号不存在')
                return redirect(url_for('post'))
            return render_template('post.html', posts=posts, info=info)
        if info == 'postname':
            posts = Post.query.filter_by(postname=date).first()
            if posts is None:
                flash('岗位不存在')
                return redirect(url_for('post'))
            return render_template('post.html', posts=posts, info=info)

    posts = Post.query.all()

    return render_template('post.html', posts=posts, info=1)


@app.route('/post_delete/<int:postID>', methods=['POST'])
@login_required  # 登录保护
def post_delete(postID):
    staff = Staff.query.filter_by(postID=postID).first()
    if staff is not None:
        flash('该岗位内存在员工无法删除')
        return redirect(url_for('post'))
    post = Post.query.get_or_404(postID)
    db.session.delete(post)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('post'))


@app.route('/post_alter/<int:postID>', methods=['GET', 'POST'])
@login_required
def post_alter(postID):
    post = Post.query.get_or_404(postID)
    if request.method == 'POST':
        postname = request.form.get('postname')
        posttype = request.form.get('posttype')
        establishment = request.form.get('establishment')
        if establishment == '':
            establishment = None
        post.postname = postname
        post.posttype = posttype
        post.establishment = establishment
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('post'))

    return render_template('post_alter.html', post=post)


@app.route('/post_add', methods=['GET', 'POST'])
@login_required
def post_add():
    if request.method == 'POST':
        postname = request.form.get('postname')
        posttype = request.form.get('posttype')
        establishment = request.form.get('establishment')
        if establishment == '':
            establishment = None
        post = Post(postname=postname, posttype=posttype, establishment=establishment)
        db.session.add(post)
        db.session.commit()
        flash('新建成功')
        return redirect(url_for('post'))
    return render_template('post_add.html')

#-----------------------------------------------------------------------
"""
打卡sign_in   -- 按部门分类
      -- 迟到情况
      -- 正常
"""


@app.route('/sign_in', methods=['GET', 'POST'])
@login_required
def sign_in():  # 员工打卡记录界面
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'departmentID':
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('sign_in'))
                return render_template('sign_in.html',departments=departments,info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('sign_in'))
                return render_template('sign_in.html',departments=departments,info=info)
        departments = Department.query.all()
        info = 1
        return render_template('sign_in.html',  departments=departments, info=info)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        return render_template('sign_in.html', departments=departments)


@app.route('/staff_sign_in/<int:departmentID>', methods=['GET','POST'])
@login_required
def staff_sign_in(departmentID):  #打卡记录
    # 获取当前时间
    now_time = datetime.datetime.now()
    # 格式化时间字符串
    begin_date = now_time.strftime("%Y-%m-1")
    end_date = now_time.strftime("%Y-%m-%d")
    department = Department.query.filter_by(departmentID=departmentID).first()
    if request.method == 'POST':
        begin_date = request.form.get('begin_date')
        end_date = request.form.get('end_date')
        staff = Staff.query.filter_by(departmentID=departmentID).all()
        sign_in_s = Sign_in.query.filter(Sign_in.late_date >= begin_date).filter(Sign_in.late_date <= end_date).all()
        return render_template('staff_sign_in.html', sign_in_s=sign_in_s, staff=staff,department=department)
    else:
        staff = Staff.query.filter_by(departmentID=departmentID).all()
        sign_in_s = Sign_in.query.filter_by(late_date = end_date).all()

        return render_template('staff_sign_in.html', sign_in_s=sign_in_s, staff=staff,department=department)


#-----------------------------------------------------------------------
"""
加班overtime   -- 按部门分类
      -- 加班情况
      -- 正常
"""


@app.route('/overtime', methods=['GET', 'POST'])
@login_required
def overtime():  # 员工打卡记录界面
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'departmentID':
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('overtime'))
                return render_template('overtime.html',departments=departments,info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('overtime'))
                return render_template('overtime.html',departments=departments,info=info)
        departments = Department.query.all()
        info = 1
        return render_template('overtime.html',  departments=departments, info=info)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        return render_template('overtime.html', departments=departments)


@app.route('/staff_overtime/<int:departmentID>', methods=['GET','POST'])
@login_required
def staff_overtime(departmentID):  #打卡记录
    # 获取当前时间
    now_time = datetime.datetime.now()
    # 格式化时间字符串
    begin_date = now_time.strftime("%Y-%m-1")
    end_date = now_time.strftime("%Y-%m-%d")
    department = Department.query.filter_by(departmentID=departmentID).first()
    if request.method == 'POST':
        begin_date = request.form.get('begin_date')
        end_date = request.form.get('end_date')
        staff = Staff.query.filter_by(departmentID=departmentID).all()
        overtimes = Overtime.query.filter(Overtime.overtime_date >= begin_date).filter(Overtime.overtime_date <= end_date).all()
        return render_template('staff_overtime.html', overtimes=overtimes, staff=staff,department=department)
    else:
        staff = Staff.query.filter_by(departmentID=departmentID).all()
        overtimes = Overtime.query.filter_by(overtime_date = end_date).all()

        return render_template('staff_overtime.html', overtimes=overtimes, staff=staff,department=department)


#---------------------------------------------------------------------
"""
休假 
普通用户 添加休假申请、查看自己的休假申请（详情）、修改审核中的休假申请（修改）
管理员 添加休假申请、查看所有人的休假申请（详情）、修改审核中的休假申请（修改）、审核休假申请（审核）
"""
@app.route('/holiday', methods=['GET', 'POST'])
@login_required
def holiday():  # 员工打卡记录界面
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date).first()
                if staffs is None:
                    flash('员工号不存在')
                    return redirect(url_for('holiday'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                holiday = Holiday.query.filter_by(userID=date).all()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts,info=info,holidays=holiday)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('holiday'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                holiday = Holiday.query.filter_by(userID=staffs.userID).all()
                return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts,info=info,holidays=holiday)
            if info == 'IDnumber':
                staffs = Staff.query.filter_by(IDnumber=date).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('holiday'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                holiday = Holiday.query.filter_by(userID=staffs.userID).all()
                return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts,info=info,holidays=holiday)
            if info == 'departmentID':
                staffs = Staff.query.filter_by(departmentID=date).all()
                if staffs is None:
                    flash('部门号不存在')
                    return redirect(url_for('holiday'))
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('holiday'))
                posts = Post.query.all()
                holiday = Holiday.query.filter_by().all()
                return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts,info=info,holidays=holiday)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('holiday'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID).all()
                posts = Post.query.all()
                holiday = Holiday.query.filter_by().all()
                return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts,info=info,holidays=holiday)
        staffs = Staff.query.filter_by(now=True).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        holiday=Holiday.query.filter_by().all()
        return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts, info=info,holidays=holiday)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        posts = Post.query.filter_by(postID=staffs.postID).first()
        holiday = Holiday.query.filter_by(userID=current_user.userID).all()
        return render_template('holiday.html', staffs=staffs, departments=departments, posts=posts,holidays=holiday)

@app.route('/holiday_add/<int:userID>', methods=['GET', 'POST'])
@login_required
def holiday_add(userID):
    staff = Staff.query.get_or_404(userID)
    if request.method == 'POST':
        cause = request.form.get('cause')
        starting_time = request.form.get('starting_time')
        ending_time = request.form.get('ending_time')
        state = '审核中'
        holiday = Holiday(userID=userID,cause=cause,starting_time=starting_time,ending_time=ending_time,state=state)
        db.session.add(holiday)
        db.session.commit()
        flash('添加成功')
        return redirect(url_for('holiday'))
    return render_template('holiday_add.html',staff=staff)

@app.route('/holiday_staff/<int:userID>/<int:id>')
@login_required
def holiday_staff(userID, id):
    holiday = Holiday.query.get_or_404(id)
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('holiday_staff.html', holiday=holiday, staff=staff)

@app.route('/holiday_change/<int:userID>/<int:id>', methods=['GET', 'POST'])
@login_required
def holiday_change(userID, id):
    holiday = Holiday.query.filter_by(userID=userID, id=id).first()
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        cause = request.form.get('cause')
        starting_time = request.form.get('starting_time')
        ending_time = request.form.get('ending_time')
        holiday.cause = cause
        holiday.starting_time = starting_time
        holiday.ending_time = ending_time
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('holiday'))
    return render_template('holiday_change.html', holiday=holiday, staff=staff)

@app.route('/holiday_state/<int:userID>/<int:id>')
@login_required
def holiday_state(userID, id):
    holiday = Holiday.query.get_or_404(id)
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('holiday_state.html', holiday=holiday, staff=staff)


@app.route('/holiday_pass/<int:userID>/<int:id>',methods=['POST'])
@login_required
def holiday_pass(id,userID):
    holiday = Holiday.query.get_or_404(id)
    holiday.state = '审核通过'
    db.session.commit()
    flash('审核通过')
    return redirect(url_for('holiday'))

@app.route('/holiday_no_pass/<int:userID>/<int:id>',methods=['GET','POST'])
@login_required
def holiday_no_pass(id,userID):
    holiday = Holiday.query.get_or_404(id)
    staff = Staff.query.get_or_404(userID)
    if request.method == 'POST':
        holiday.state = '审核不通过'
        no_pass_cause = request.form.get('no_pass_cause')
        holiday.no_pass_cause=no_pass_cause
        db.session.commit()
        flash('审核不通过')
        return redirect(url_for('holiday'))
    return render_template('holiday_no_pass.html',staff=staff)

#---------------------------------------------------------------------
"""
出差 
普通用户 添加出差申请、查看自己的出差申请（详情）、修改审核中的出差申请（修改）
管理员 添加出差申请、查看所有人的出差申请（详情）、修改审核中的出差申请（修改）、审核出差申请（审核）
"""
@app.route('/evection', methods=['GET', 'POST'])
@login_required
def evection():  # 员工打卡记录界面
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date).first()
                if staffs is None:
                    flash('员工号不存在')
                    return redirect(url_for('evection'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                evection = Evection.query.filter_by(userID=date).all()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                return render_template('evection.html', staffs=staffs, departments=departments, posts=posts,info=info,evections=evection)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('evection'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                evection = Evection.query.filter_by(userID=staffs.userID).all()
                return render_template('evection.html', staffs=staffs, departments=departments, posts=posts,info=info,evections=evection)
            if info == 'IDnumber':
                staffs = Staff.query.filter_by(IDnumber=date).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('evection'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                evection = Evection.query.filter_by(userID=staffs.userID).all()
                return render_template('evection.html', staffs=staffs, departments=departments, posts=posts,info=info,evections=evection)
            if info == 'departmentID':
                staffs = Staff.query.filter_by(departmentID=date).all()
                if staffs is None:
                    flash('部门号不存在')
                    return redirect(url_for('evection'))
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('evection'))
                posts = Post.query.all()
                evection = Evection.query.filter_by().all()
                return render_template('evection.html', staffs=staffs, departments=departments, posts=posts,info=info,evections=evection)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('evection'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID).all()
                posts = Post.query.all()
                evection = Evection.query.filter_by().all()
                return render_template('evection.html', staffs=staffs, departments=departments, posts=posts,info=info,evections=evection)
        staffs = Staff.query.filter_by(now=True).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        evection=Evection.query.filter_by().all()
        return render_template('evection.html', staffs=staffs, departments=departments, posts=posts, info=info,evections=evection)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        posts = Post.query.filter_by(postID=staffs.postID).first()
        evection = Evection.query.filter_by(userID=current_user.userID).all()
        return render_template('evection.html', staffs=staffs, departments=departments, posts=posts,evections=evection)

@app.route('/evection_add/<int:userID>', methods=['GET', 'POST'])
@login_required
def evection_add(userID):
    staff = Staff.query.get_or_404(userID)
    if request.method == 'POST':
        cause = request.form.get('cause')
        starting_time = request.form.get('starting_time')
        ending_time = request.form.get('ending_time')
        state = '审核中'
        evection = Evection(userID=userID,cause=cause,starting_time=starting_time,ending_time=ending_time,state=state)
        db.session.add(evection)
        db.session.commit()
        flash('添加成功')
        return redirect(url_for('evection'))
    return render_template('evection_add.html',staff=staff)

@app.route('/evection_staff/<int:userID>/<int:id>')
@login_required
def evection_staff(userID, id):
    evection = Evection.query.get_or_404(id)
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('evection_staff.html', evection=evection, staff=staff)

@app.route('/evection_change/<int:userID>/<int:id>', methods=['GET', 'POST'])
@login_required
def evection_change(userID, id):
    evection = Evection.query.filter_by(userID=userID, id=id).first()
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        cause = request.form.get('cause')
        starting_time = request.form.get('starting_time')
        ending_time = request.form.get('ending_time')
        evection.cause = cause
        evection.starting_time = starting_time
        evection.ending_time = ending_time
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('evection'))
    return render_template('evection_change.html', evection=evection, staff=staff)

@app.route('/evection_state/<int:userID>/<int:id>')
@login_required
def evection_state(userID, id):
    evection = Evection.query.get_or_404(id)
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('evection_state.html', evection=evection, staff=staff)


@app.route('/evection_pass/<int:userID>/<int:id>',methods=['POST'])
@login_required
def evection_pass(id,userID):
    evection = Evection.query.get_or_404(id)
    evection.state = '审核通过'
    db.session.commit()
    flash('审核通过')
    return redirect(url_for('evection'))

@app.route('/evection_no_pass/<int:userID>/<int:id>',methods=['GET','POST'])
@login_required
def evection_no_pass(id,userID):
    evection = Evection.query.get_or_404(id)
    staff = Staff.query.get_or_404(userID)
    if request.method == 'POST':
        evection.state = '审核不通过'
        no_pass_cause = request.form.get('no_pass_cause')
        evection.no_pass_cause=no_pass_cause
        db.session.commit()
        flash('审核不通过')
        return redirect(url_for('evection'))
    return render_template('evection_no_pass.html',staff=staff)

